//
//  PCJoinPhotoMatch.m
//  PhotoCircle
//
//  Created by wujungao on 12/10/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCJoinPhotoMatchVC.h"
#import "joinCell.h"
#import "PCPhotoUploadVC.h"
#import "PCJoinPhotoMatchUploadVC.h"
#import "fetchData.h"
#import "availableGamesModel.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "GMTipsHelper.h"

@interface PCJoinPhotoMatchVC ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (strong, nonatomic)UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *btnView;
@property (weak, nonatomic) IBOutlet UIButton *photographBtn;
@property (weak, nonatomic) IBOutlet UIButton *albumBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

- (IBAction)backBtnAction:(UIButton *)sender;
- (IBAction)photographBtnAction:(UIButton *)sender;
- (IBAction)albumBtnAction:(UIButton *)sender;
- (IBAction)cancelBtnAction:(UIButton *)sender;

//@property(nonatomic,assign)vcType vcstyle;
@property(nonatomic,strong)NSArray *gamelistArray;

@end

@implementation PCJoinPhotoMatchVC

#pragma mark - PCJoinPhotoMatchVC method
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    MCShowNavBar();
    MCShowNavBackButton();
    MCHiddenTabBar();
    MCHiddenBottomView();
    MCHiddenPlusBackgroundView();
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.translucent = NO;

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [self.view addSubview:lineView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self fetchGameList];
    [self configTableView];
    [self configTitleLabel];
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(void)passVCType:(vcType)vcstyle{
//    
//    self.vcstyle=vcstyle;
//}

#pragma mark - config views
-(void)configBottomView{
    
    self.bottomView.backgroundColor=[UIColor colorWithWhite:0 alpha:0.5];
    self.bottomView.hidden=YES;
}

-(void)configTableView{
    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

-(void)configTitleLabel{
    
    self.titleLabel.text=@"参赛";
}

#pragma mark - fetch data
-(void)fetchGameList{
    
    [GMTipsHelper showLoading];
    
    [[fetchData shared] fetchGameListSuccessBlock:^(NSMutableArray *gamelistArray) {
        
        [GMTipsHelper showDismiss];
        self.gamelistArray=gamelistArray;
        if(self.gamelistArray.count==0){
            
            [GMTipsHelper showSearchEmpty];
        }
        
        [self.tableView reloadData];
        
    } failBlock:^{
        
        [GMTipsHelper showDismiss];
        [GMTipsHelper showBadNetwork];
    }];
}

#pragma mark - property
-(UITableView *)tableView{
    
    CGFloat y= 0.5;
    CGRect rect=CGRectMake(0, y, SCREEN_W, SCREEN_H-y);
    
    if(_tableView==nil){
        
        _tableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        _tableView.backgroundColor = PCColorC12;
        UINib *cellNib=[UINib nibWithNibName:@"joinCell" bundle:[NSBundle mainBundle]];
        [_tableView registerNib:cellNib forCellReuseIdentifier:@"joinCell"];
    }
    
    return _tableView;
}

#pragma mark - button action
- (IBAction)backBtnAction:(UIButton *)sender {
    [GMTipsHelper showDismiss];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)photographBtnAction:(UIButton *)sender {
    //拍照上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (IBAction)albumBtnAction:(UIButton *)sender {
    //相册上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (IBAction)cancelBtnAction:(UIButton *)sender {
    
    [self hiddenBottomView];
}

#pragma mark - image picker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *imageURL=[info objectForKey:UIImagePickerControllerReferenceURL];
    __block NSDictionary *metadataDict;
    
    if(picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){
        //相册
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            metadataDict=representation.metadata;
            
            //upload图片
            [self uploadImage:image withImageMetaData:metadataDict];
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageURL
                       resultBlock:resultblock
                      failureBlock:nil];
        
    }else{
        //拍照
        metadataDict=[info valueForKey:UIImagePickerControllerMediaMetadata];
        //upload图片
        [self uploadImage:image withImageMetaData:metadataDict];
    }
}

#pragma mark - tableView delegate and datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.gamelistArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    joinCell *cell=[tableView dequeueReusableCellWithIdentifier:@"joinCell"];
    NSString *text= (((availableGamesModel *)self.gamelistArray[indexPath.item]).title);
    if(!cell){
        UINib *cellNib=[UINib nibWithNibName:@"joinCell" bundle:[NSBundle mainBundle]];
        [tableView registerNib:cellNib forCellReuseIdentifier:@"joinCell"];
    }
    if (indexPath.row + 1 ==self.gamelistArray.count) {
        [cell configCellTheLastCell:YES TextLabelWithText:text];
    }else{
        [cell configCellTheLastCell:NO TextLabelWithText:text];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //选中时，弹出对应窗口
    [self showBottomView];
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - private method
-(void)showBottomView{
    
    self.bottomView.hidden=NO;
    [self.view bringSubviewToFront:self.bottomView];
}

-(void)hiddenBottomView{
    
    self.bottomView.hidden=YES;
}

-(void)uploadImage:(UIImage *)image withImageMetaData:(NSDictionary *)imageMetaData{
    
    UIStoryboard *photoUploadStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCJoinPhotoMatchUploadVC *photoUploadVC=[photoUploadStory instantiateViewControllerWithIdentifier:@"PCJoinPhotoMatchUploadVC"];
    
    [photoUploadVC passImage:image withImageMetaDat:imageMetaData];
    
    [self.navigationController pushViewController:photoUploadVC animated:YES];
    
    [self hiddenBottomView];
}

@end
